package com.retoc.oawx.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.rabbitmq.client.Return;
import com.retoc.oawx.common.util.R;
import com.retoc.oawx.domain.Materials;
import com.retoc.oawx.domain.MaterialsType;
import com.retoc.oawx.domain.req.MaterialsReq;
import com.retoc.oawx.exception.OAException;
import com.retoc.oawx.service.MaterialsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.nio.file.Paths;
import java.security.PublicKey;
import java.util.ArrayList;

@RestController
@RequestMapping("/materials")
@Api("物资模块接口")
@Slf4j
public class MaterialsController {

    @Autowired
    MaterialsService materialsService;

    @Value("${oawx.image-folder}")
    private String imageFolder;

    @Value("${oawx.image-path}")
    private String imagePath;

    @PostMapping("/insertMaterials")
    @ApiOperation("新增物资")
    public R insertMaterials(@RequestParam("photo") MultipartFile file,@Valid MaterialsReq req, @RequestHeader("token") String token) {
        if (file == null) {
            return R.error("没有上传图片");
        }
        String fileName = file.getOriginalFilename().toLowerCase();
        if (!fileName.endsWith(".jpg")) {
            return R.error("必须提交JPG格式照片");
        }else {
            String path = imageFolder + "/" + fileName;
            try {
                file.transferTo(Paths.get(path));
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new OAException("图片保存错误，请重试");
            }
//            finally {
//                FileUtil.del(path);
//            }
        }
        String photo=imagePath+fileName;
        Materials materials=new Materials();
        if (!req.getDescription().isEmpty()&&!req.getDescription().isBlank()){
            materials.setDescription(req.getDescription());
        }
        if (!req.getBrand().isEmpty()&&!req.getBrand().isBlank()){
            materials.setBrand(req.getBrand());
        }
//        if (!req.getUrl().isEmpty()&&!req.getUrl().isBlank()){
//            materials.setUrl(req.getUrl());
//        }
        materials.setType(req.getType());
        materials.setName(req.getName());
        materials.setQty(req.getQty());
        materials.setPrice(req.getPrice());
        materials.setUnit(req.getUnit());
        materials.setPhoto(photo);
        int row=materialsService.insertMaterials(materials);
        if (row!=1){
            throw new OAException("添加失败");
        }
        return R.ok();
    }

    @PostMapping("/updateMaterials")
    @ApiOperation("修改物资信息")
    public R updateMaterials(@RequestParam("photo") MultipartFile file,@Valid MaterialsReq req, @RequestHeader("token") String token) {
        if (file == null) {
            return R.error("没有上传图片");
        }
        String fileName = file.getOriginalFilename().toLowerCase();
        if (!fileName.endsWith(".jpg")) {
            return R.error("必须提交JPG格式照片");
        }else {
            String path = imageFolder + "/" + fileName;
            try {
                file.transferTo(Paths.get(path));
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new OAException("图片保存错误，请重试");
            }
//            finally {
//                FileUtil.del(path);
//            }
        }
        String photo=imagePath+fileName;
        Materials materials = materialsService.selectMaterialsByid(req.getId());
        String oldFileName=materials.getPhoto().substring(materials.getPhoto().lastIndexOf('\\')+1);
        String old=imagePath+oldFileName;
        if (!req.getDescription().isEmpty()&&!req.getDescription().isBlank()){
            materials.setDescription(req.getDescription());
        }
        if (!req.getBrand().isEmpty()&&!req.getBrand().isBlank()){
            materials.setBrand(req.getBrand());
        }
//        if (!req.getUrl().isEmpty()&&!req.getUrl().isBlank()){
//            materials.setUrl(req.getUrl());
//        }
        materials.setType(req.getType());
        materials.setName(req.getName());
        materials.setQty(req.getQty());
        materials.setPrice(req.getPrice());
        materials.setUnit(req.getUnit());
        materials.setPhoto(photo);
        int row=materialsService.updateMaterials(materials);
        if (row!=1){
            throw new OAException("添加失败");
        }
        FileUtil.del(old);
        return R.ok();
    }

    @PostMapping("/updateMaterialsnop")
    @ApiOperation("修改物资信息")
    public R updateMaterialsnop(@Valid @RequestBody MaterialsReq req, @RequestHeader("token") String token) {

        Materials materials = materialsService.selectMaterialsByid(req.getId());
        if (!req.getDescription().isEmpty()&&!req.getDescription().isBlank()){
            materials.setDescription(req.getDescription());
        }
        if (!req.getBrand().isEmpty()&&!req.getBrand().isBlank()){
            materials.setBrand(req.getBrand());
        }
//        if (!req.getUrl().isEmpty()&&!req.getUrl().isBlank()){
//            materials.setUrl(req.getUrl());
//        }
        materials.setType(req.getType());
        materials.setName(req.getName());
        materials.setQty(req.getQty());
        materials.setPrice(req.getPrice());
        materials.setUnit(req.getUnit());
        int row=materialsService.updateMaterials(materials);
        if (row!=1){
            throw new OAException("添加失败");
        }
        return R.ok();
    }

    @GetMapping("/getType")
    @ApiOperation("查询所有分类")
    public R getType(){
        ArrayList<MaterialsType> types=materialsService.getType();
        return R.ok().put("result",types);
    }

    @GetMapping("/getMaterials")
    @ApiOperation("查询分类下所有物资")
    public R getMaterials(@RequestParam int typeId,@RequestParam int length,@RequestParam int page){
        int start=(page-1)*length;
        ArrayList<Materials> materials = materialsService.selectMaterials(typeId,length,start);
        return R.ok().put("result",materials);
    }

    @GetMapping("/getMaterialById")
    @ApiOperation("按id号查询指定物资")
    public R getMaterialById(@RequestParam int id){
        Materials materials=materialsService.selectMaterialsByid(id);
        return R.ok().put("result", materials);
    }
}
